<?php

class NoticeController extends AdminController
{
	public function actionIndex()
	{
		$c = new CDbCriteria();
		$c->order = 'created_date DESC';
		$items = Notice::model()->findAll($c);
		$newItem= new Notice();
		if (isset($_POST['Notice'])) {
			switch($_POST['action']) {
				case 'create':
					$this->create($newItem, $_POST['Notice']['new']);
					break;
				case 'update':
					$this->update($items, $_POST['Notice']);
					break;
			}

		}
		
		$this->render('index',array(
			'items'=>$items,
			'newItem'=>$newItem,
		));	
	}

	public function create($model, $data)
	{
		$model->attributes = $data;
		$model->created_date = Helper::parseTime($model->created_date);
		
		if ($model->save()) {
			Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
			$this->redirect(array('index'));
		}
	}

	public function update(&$models, $datas)
	{
		// validate models
		$models = array();
		$hasError = false;
		foreach($datas as $id => $data) {
			$model = $this->loadModel($id);
			$model->attributes = $data;
			$model->created_date = Helper::parseTime($model->created_date);
			
			if (!$model->validate()) {
				$hasError = true;
			}
				
			$models[] = $model;
		}
		
		// save models
		if (!$hasError) {
			foreach($models as $model) {
				$model->save();
			}
			Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
			$this->redirect(array('index'));
		}
	}

	public function actionDelete($id) {
		$this->loadModel($id)->delete();
		Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
		$this->redirect(array('index'));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Page the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id) {
		$model = Notice::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

}